import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Card, Breadcrumb, Form, Input, Button, Space, Radio, Upload, Modal, message } from "antd";
import Channels from "components/Channels";
import ReactQuill from "react-quill"; // ES6 富文本
import "react-quill/dist/quill.snow.css"; // ES6
import styles from "./index.module.scss";
import { addArticle, getArticleApi, editArticle } from "api/article";
export default class Publish extends Component {
  state = {
    type: 1,
    fileList: [],
    isModalVisible: false,
    previewUrl: null,
  };
  render() {
    return (
      <div className={styles.publish}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>发布文章</Breadcrumb.Item>
            </Breadcrumb>
          }
          style={{ marginBottom: 20 }}
        >
          {/* 表单部分 */}
          <Form
            ref={form => (this.formRef = form)}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 1, content: "" }}
            onFinish={this.submitHandle}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: "请输入文章标题" }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: "请选择文章频道" }]}
            >
              <Channels></Channels>
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={-1}>无图</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Upload
                name="image"
                listType="picture-card"
                className="avatar-uploader"
                action="http://geek.itheima.net/v1_0/upload"
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange} //上传文件变化
                maxCount={this.state.type}
                fileList={this.state.fileList}
                onPreview={this.onPreview}
                accept=".jpg,.png"
              >
                上传
              </Upload>
            </Form.Item>
            {/* 富文本 */}
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: "请输入内容" }]}
            >
              <ReactQuill />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {this.props.match.params.id ? "修改" : "发布"}文章
                </Button>
                <Button size="large" type="ghost" onClick={this.onAddDraft}>
                  存为草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
        {/* 图片预览弹层 */}
        <Modal visible={this.state.isModalVisible} footer={null} onCancel={this.onCancel}>
          <img src={this.state.previewUrl} style={{ width: "100%", padding: 20 }} alt=""></img>
        </Modal>
      </div>
    );
  }
  // 编辑回显
  getArticle = async id => {
    let res = await getArticleApi(id);
    this.formRef.setFieldsValue({ ...res, type: res.cover.type || -1 });
    this.setState({
      fileList: res.cover.images.map(item => {
        return { url: item };
      }),
    });
  };

  componentDidMount() {
    const id = this.props.match.params.id;
    if (!id) return;
    this.getArticle(id);
  }

  onSave = async (values, draft) => {
    //图片校验
    if (values.type !== this.state.fileList.length && values.type !== -1) {
      return Promise.reject();
    }
    const params = {
      ...values,
      cover: {
        type: values.type !== -1 ? values.type : 0,
        image: this.state.fileList.map(item => item.response.data.url),
      },
      draft,
    };
    if (this.props.match.params.id) {
      //修改文章
      params.id = this.props.match.params.id;
      console.log(params);
      let res = await editArticle(params);
      console.log(res);
    } else {
      //发布文章
      await addArticle(params);
    }
  };
  /* 表单提交 */
  submitHandle = async values => {
    await this.onSave(values, false);
    message.success("操作成功~");
    this.props.history.push("/home/article");
  };
  /* radio 变换 */
  radioChange = e => {
    this.setState({
      type: e.target.value,
      fileList: e.target.value !== 3 ? [] : this.state.fileList,
    });
  };
  // 图片变化 上传
  handleChange = ({ file, fileList }) => {
    this.setState({ fileList: fileList });
  };
  // 预览
  onPreview = ({ response }) => {
    this.setState({
      isModalVisible: true,
      previewUrl: response.url || response.data.url,
    });
  };
  // 关闭
  onCancel = () => {
    this.setState({
      isModalVisible: false,
    });
  };
  // 图片上传前的操作
  beforeUpload = file => {
    console.log(file);
    const ImageType = ["image/jpeg", "image/png"];
    if (!ImageType.includes(file.type)) {
      message.warning("只能上传jpg,png格式的图片！");
      return false;
    } else {
      return true;
    }
  };
  // 存为草稿
  onAddDraft = async () => {
    try {
      let values = await this.formRef.validateFields();
      await this.onSave(values, true);
      message.success("添加草稿成功！");
      this.props.history.push("/home/article");
    } catch (error) {
      console.log(error);
      message.error("请填写相关内容或者上传相对应图片数量~");
    }
  };
}
